package com.gict.antifraudback.controller.web.carousel;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gict.antifraudback.entity.Carousel;
import com.gict.antifraudback.exception.MyException;
import com.gict.antifraudback.result.ResultEnum;
import com.gict.antifraudback.result.ResultView;
import com.gict.antifraudback.service.CarouselService;
import com.gict.antifraudback.vo.CarouselVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;

/**
 * @author ThinkPad
 */
@RestController
@Slf4j
@RequestMapping("/wapi/carousel")
public class CarouselController {

    @Autowired
    private CarouselService carouselService;

    @GetMapping("/getList")
    public ResultView getList(CarouselVo carouselVo) {
        return ResultView.ok(carouselService.page(new Page<>(carouselVo.getCurrent(), carouselVo.getPageSize())));
    }

    @GetMapping("/get")
    public ResultView get(@Valid @NotNull Integer id) {
        Carousel carousel = carouselService.getById(id);
        if (carousel == null) {
            throw new MyException("轮播图不存在");
        }
        return ResultView.ok(carousel);
    }

    @PostMapping("/delete")
    public ResultView delete(@RequestBody ArrayList<Integer> ids) {
        log.info("carouselVo:{}", ids);
        for (Integer id : ids) {
            carouselService.removeById(id);
        }
        return ResultView.okMsg("删除成功");
    }

    @PostMapping("/add")
    public ResultView add(@Valid @RequestBody Carousel carousel) {
        carouselService.save(carousel);
        return ResultView.ok();
    }

    @PostMapping("/update")
    public ResultView update(@RequestBody @Valid Carousel carousel) {
        Carousel update = carouselService.getById(carousel.getId());
        if (update == null) {
            return ResultView.error(ResultEnum.CODE_2, "数据不存在！");
        }
        carouselService.updateById(carousel);
        return ResultView.ok();
    }
}
